// 浏览器 LocalStorage 相关方法
import dayjs from 'dayjs';
import { getBrandIdCookie } from '@biztools/info';

/**
 * 保存信息
 * @param {String} name  LocalStorage Item 的名字
 * @param {Object} obj  LocalStorage Item 的数据
 * @param {Timestamp} outTime 失效时间，时间戳
 */
export const setInfo = (name, obj, outTime) => {
    const time = outTime || dayjs().add(1, 'days').unix();
    // 先删除，再存，防止报错
    clearInfo(name);
    const _param = {
        outTime: time,
        data: obj,
    };
    localStorage.setItem(`tech-${name}`, JSON.stringify(_param));
};

/**
 * 获取 LocalStorage Item 的数据
 * @param {String} name  LocalStorage Item 的名字
 */
export const getInfo = (name) => {
    const _item = JSON.parse(localStorage.getItem(`tech-${name}`));
    const _now = dayjs().unix();
    if (!_item) {
        return null;
    }
    if (_item.outTime >= _now) {
        clearInfo(name);
        return _item.data;
    } else {
        clearInfo(name);
        return null;
    }
};

/**
 * 清除 LocalStorage Item 的信息
 * @param {String} name  LocalStorage Item 的名字
 */
export const clearInfo = (name) => {
    // 删除
    localStorage.removeItem(`tech-${name}`);
};

/**
 * 保存当前品牌的充值协议状态
 * @param {Boolean} flag
 */
export const setBrandProtocolState = (flag) => {
    const brandId = getBrandIdCookie();
    localStorage.setItem(`tech-protocol-${brandId}`, flag);
};

/**
 * 获取当前品牌的充值协议状态
 */
export const getBrandProtocolState = () => {
    const brandId = getBrandIdCookie();
    const val = localStorage.getItem(`tech-protocol-${brandId}`);
    return val === null ? false : val;
};

const LOCAL_CART = 'local-cart';

/**
 * 保存本地购物车数据
 * @param {Object} obj 购物车数据对象
 */
export const setLocalCart = (obj) => {
    setInfo(LOCAL_CART, obj);
};

/**
 * 获取本地购物车数据
 */
export const getLocalCart = () => {
    return getInfo(LOCAL_CART);
};
